//
//  UIViewController+JJExtension.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/8.
//

import Foundation

public extension UIViewController {
    
    /// 添加导航栏
    /// - Parameters:
    ///   - backImg: 返回按钮图片
    ///   - titleFont: 标题字体
    ///   - titleColor: 标题颜色
    func addNavigationView(backImg: String, titleFont: UIFont, titleColor: UIColor) {
        // 返回按钮
        if (self.navigationController?.viewControllers.count ?? 0) > 1 {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: backImg)?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(goBack))
        }
        // 标题样式
        let titleDict: [NSAttributedString.Key : Any] = [.font: titleFont, .foregroundColor: titleColor]
        navigationController?.navigationBar.titleTextAttributes = titleDict
        navigationController?.navigationBar.barTintColor = .black
        navigationController?.navigationBar.isTranslucent = false
        // 去除导航栏底部黑线
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        // 返回手势会与抽屉效果的手势冲突
        navigationController?.interactivePopGestureRecognizer?.delegate = (self as? any UIGestureRecognizerDelegate)
    }
    
    /// 返回按钮点击事件
    @objc func goBack() {
        self.navigationController?.popViewController(animated: true)
    }
    
    /// 设置左边按钮
    /// - Parameter leftButton: 可以是string、button、uiview、uiimage
    func setLeftButton(leftButton: Any) {
        let textAttrs: [NSAttributedString.Key : Any] = [.font: UIFont.customerFont(name: .pingFangSCRegular, size: 15), .foregroundColor: UIColor.hex("#333333")]
        if type(of: leftButton) == UIImage.self, let image = leftButton as? UIImage {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem.creat(target: self, action: #selector(leftButtonClick(sender:)), image: image, highImage: image)
            self.navigationItem.leftBarButtonItem?.setTitleTextAttributes(textAttrs, for: .normal)
            return
        }
        if type(of: leftButton) == String.self, let title = leftButton as? String {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(leftButtonClick(sender:)))
            self.navigationItem.leftBarButtonItem?.setTitleTextAttributes(textAttrs, for: .normal)
            return
        }
        if type(of: leftButton) == UIButton.self, let btn = leftButton as? UIButton {
            btn.addTarget(self, action: #selector(leftButtonClick(sender:)), for: .touchUpInside)
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
            return
        }
        if type(of: leftButton) == UIView.self, let left = leftButton as? UIView {
            left.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftButtonClick(sender:))))
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: left)
            return
        }
    }
    
    /// 左边按钮点击事件
    /// - Parameter sender: 按钮
    @objc open func leftButtonClick(sender: AnyObject) {
        
    }
    
    /// 设置右边按钮
    /// - Parameter rightButton: 可以是string、button、uiview、uiimage
    func setRightButton(rightButton: Any) {
        let textAttrs: [NSAttributedString.Key : Any] = [.font: UIFont.customerFont(name: .pingFangSCRegular, size: 15), .foregroundColor: UIColor.hex("#333333")]
        if type(of: rightButton) == UIImage.self, let image = rightButton as? UIImage {
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.creat(target: self, action: #selector(rightButtonClick(sender:)), image: image, highImage: image)
            self.navigationItem.rightBarButtonItem?.setTitleTextAttributes(textAttrs, for: .normal)
            return
        }
        if type(of: rightButton) == String.self, let title = rightButton as? String {
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(rightButtonClick(sender:)))
            self.navigationItem.rightBarButtonItem?.setTitleTextAttributes(textAttrs, for: .normal)
            return
        }
        if type(of: rightButton) == UIButton.self, let btn = rightButton as? UIButton {
            btn.addTarget(self, action: #selector(rightButtonClick(sender:)), for: .touchUpInside)
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
            return
        }
        if type(of: rightButton) == UIView.self, let left = rightButton as? UIView {
            left.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightButtonClick(sender:))))
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: left)
            return
        }
    }
    
    /// 右边按钮点击事件
    /// - Parameter sender: 按钮
    @objc open func rightButtonClick(sender: AnyObject) {
        
    }
    
    /// 设置导航栏标题view
    /// - Parameter view: 标题view
    func setTitleView(view: UIView) {
        self.navigationItem.titleView = view
    }
    
    /// 获取当前控制器
    /// - Returns: 返回控制器
    static func current() -> UIViewController? {
        var rootViewController: UIViewController?
        if var window = UIApplication.shared.keyWindow {
            if window.windowLevel != UIWindow.Level.normal {
                let windows = UIApplication.shared.windows
                for viewWindow in windows {
                    if viewWindow.windowLevel == UIWindow.Level.normal {
                        window = viewWindow
                        break
                    }
                }
            }
            rootViewController = window.rootViewController
            return getVisibleViewController(from: rootViewController)
        }
        return nil
    }
    
    private static func getVisibleViewController(from vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return getVisibleViewController(from: nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return getVisibleViewController(from: tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return getVisibleViewController(from: pvc)
            } else {
                return vc
            }
        }
    }
    
    /// 删除指定控制器
    /// - Parameter vcClassStr: 控制器类型
    /// 这里使用string做传参就是为了方便以后删除非本工程的页面
    static func deleteVC(vcClassStr: String) {
        let cts = vcClassStr.toClass()
        guard let deleteVc = cts else {
            assert(cts != nil, "没有找到\(vcClassStr)控制器")
            return
        }
        DispatchQueue.main.async {
            guard var list = current()?.navigationController?.viewControllers else {
                return
            }
             let firstIndex = list.firstIndex { item in
                return type(of: item) == deleteVc
            }
            if let index = firstIndex {
                list.remove(at: index)
            }
        }
    }
    
    /// 是否为根控制器
    /// - Returns: 返回bool
    func isRootVC() -> Bool {
        if let navigationController = self.navigationController {
            return navigationController.viewControllers.first === self
        } else {
            return false // 不在导航控制器中或者根控制器
        }
    }
}
